
// ===============================================================================================================
// -*- FRAGMENT SHADER -*-
//
// NormalMap.frag - GLSL fragment shader. Apply per-pixel lighting to the input fragment.
//
// Copyright (c) 2011 Guilherme R. Lampert
// guilherme.ronaldo.lampert@gmail.com
//
// This code is licenced under the MIT license.
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that the copyright text
// above is included in the resulting source code.
//
// ===============================================================================================================

// Input data:
varying vec4 vertexPos;

// Texture samplers:
uniform sampler2D diffuseTex; // Color texture
uniform sampler2D normalMapTex; // Normal Map texture

// Local constants:
const vec4 lightPos = vec4(0.0, 10.0, 0.0, 0.0);
const vec4 lightColor = vec4(0.99, 0.97, 0.91, 1.0);
const float lightConstantAttenuation = 0.8;
const float lightLinearAttenuation = 0.007;
const float lightQuadraticAttenuation = 0.0;

void main(void)
{
	// Normal map lookup:

	// Extract normal from the normal map texture [R = x, G = y, B = z]
	vec3 normal = texture2D(normalMapTex, gl_TexCoord[0].st).xyz;

	// Bring the xyz normal in the -1.0 to 1.0 margin
	normal = (normal - 0.5) * 2.0;

	// Finally assign the normal map to the actual normal to be used in our lighting
	normal = normalize(normal);

	// Compute lighting:

	vec3 diff = vec3(lightPos - vertexPos);

	vec3 lightDir = normalize(diff);

	float lightDist = length(diff); // Distance between light position and fragment

	float NdotL = max(dot(normal, lightDir), 0.0); // Dot product of normal and lightDir

	// Light attenuation factor
	float attenuation = 1.0 / (lightConstantAttenuation + (lightLinearAttenuation * lightDist) + (lightQuadraticAttenuation * lightDist * lightDist));

	// Add texel color
	vec4 finalColor = texture2D(diffuseTex, gl_TexCoord[0].st);

	// Put all the lighting together
	finalColor *= attenuation * (lightColor * NdotL);
	finalColor.a = 1.0;

	gl_FragColor = finalColor;
}